package com.butang.AOP;

import com.alibaba.fastjson.JSONObject;
import com.butang.pojo.OperateLog;
import com.butang.service.OperateLogServiceImpl;
import com.butang.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * ClassName: AOP
 * Package: com.butang
 * Description:
 *
 * @Author BuTang
 * @Create 2023/7/18 17:09
 * @Version 1.0
 */
@Component
@Aspect
public class AOP {
@Autowired
    private OperateLogServiceImpl operateLogService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @Around("@annotation(com.butang.AOP.Log)")
    public Object operate(ProceedingJoinPoint joinPoint) throws Throwable {
        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJwt(token);

        //操作人的username
        String username = (String) claims.get("username");

        //时间
        LocalDateTime now = LocalDateTime.now();

        //操作的类名
        String name = joinPoint.getTarget().getClass().getName();

        //操作的方法
        String name1 =  joinPoint.getSignature().getName();


        //操作方法的参数
        Object[] args = joinPoint.getArgs();
        String s = args.toString();

        Long start = System.currentTimeMillis();

        //运行切入点方法
        Object result = joinPoint.proceed();

        //方法消耗时间
        Long time = System.currentTimeMillis() - start;

        String s1 = JSONObject.toJSONString(result);

        OperateLog operateLog = new OperateLog(null,username,now,name,name1,s,s1,time);
        operateLogService.operateInsert(operateLog);

        return result ;

    }
}
